# -*- coding: utf-8 -*-

import re
import json
from core.resources import CustomerModelResource
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
from apps.pms.models import Product, Module
from apps.tms.models import TestCase
from apps.rms.packet.serializers import PacketField, PacketFieldBindingSerializer
from apps.rms.protocol.serializers import ProtocolField, ProtocolFieldBindingSerializer
from apps.pms.module.widgets import ModuleForeignKeyWidget
from apps.sys.models import DictData


class TestCaseImportResouces(CustomerModelResource):
    product = Field(attribute="product", widget=ForeignKeyWidget(Product, field="name"))
    module = Field(
        attribute="module", widget=ModuleForeignKeyWidget(Module, field="name")
    )
    step = Field(attribute="step", column_name="操作步骤")
    exp = Field(attribute="exp", column_name="预期结果")
    pcap = Field(attribute="pcap", column_name="样本数据")
    rule = Field(attribute="rule", column_name="样本规则")
    binding = Field(attribute="binding", column_name="绑定信息")

    def import_row(self, row, instance, **kwargs):
        if row.get("steps"):
            step = [i for i in row["steps"].split("\n") if (i != "")]
            exp = [i for i in row["预期结果"].split("\n") if (i != "")]
            rule = (
                [i for i in row["样本规则"].split("\n") if (i != "")]
                if row["样本规则"]
                else None
            )
            pcap = (
                [i for i in row["样本数据"].split("\n") if (i != "")]
                if row["样本数据"]
                else None
            )
            binding = (
                [i for i in row["绑定信息"].split("\n") if (i != "")]
                if row["绑定信息"]
                else None
            )
            step_info = []
            for i in range(0, len(step)):
                item = {
                    "id": i + 1,
                    "step": re.sub(r"^\d+.", "", step[i]),
                    "exp": re.sub(r"^\d+.", "", exp[i]),
                }
                if rule:
                    item["rule"] = re.sub(r"^\d+.", "", rule[i])
                if pcap:
                    item["pcap"] = re.sub(r"^\d+.", "", pcap[i])
                if binding:
                    curr_binding = json.loads(
                        re.sub(r"^\d+.", "", binding[i]).replace("'", '"')
                    )
                    if row["type"] == "11":
                        queryset = PacketField.objects.filter(
                            name=curr_binding["field"],
                            product__name=curr_binding["product"],
                            packet__name=curr_binding["packet"],
                        )
                        item["binding"] = PacketFieldBindingSerializer(
                            queryset, many=True
                        ).data
                    else:
                        queryset = ProtocolField.objects.filter(
                            name=curr_binding["field"],
                            product__name=curr_binding["product"],
                            protocol__name=curr_binding["protocol"],
                        )
                        item["binding"] = ProtocolFieldBindingSerializer(
                            queryset, many=True
                        ).data
                step_info.append(item)
            # widgets采用json.loads()方法以字符串形式加载该字段内容
            row["steps"] = json.dumps(step_info)
            row.pop("预期结果")
            row.pop("样本数据")
            row.pop("样本规则")
            row.pop("绑定信息")
        row["level"] = DictData.objects.get(
            type="tms_tc_level", label=row.get("level")
        ).value
        row["type"] = DictData.objects.get(
            type="tms_tc_type", label=row.get("type")
        ).value
        row["stage"] = DictData.objects.get(
            type="tms_tc_stage", label=row.get("stage")
        ).value
        return super().import_row(row, instance, **kwargs)

    class Meta:
        model = TestCase
        fields = (
            "number",
            "name",
            "product",
            "module",
            "level",
            "type",
            "stage",
            "isauto",
            "precondition",
            "steps",
            "remark",
        )
        import_id_fields = ("number",)
        export_order = fields


class TestCaseExportResouces(CustomerModelResource):
    product = Field(attribute="product", widget=ForeignKeyWidget(Product, field="name"))
    module = Field(attribute="module", widget=ForeignKeyWidget(Module, field="name"))
    step = Field(column_name="操作步骤")
    exp = Field(column_name="预期结果")
    pcap = Field(column_name="样本数据")
    rule = Field(column_name="样本规则")
    binding = Field(column_name="绑定信息")

    class Meta:
        model = TestCase
        fields = (
            "number",
            "name",
            "product",
            "module",
            "level",
            "type",
            "stage",
            "isauto",
            "precondition",
            "step",
            "exp",
            "pcap",
            "rule",
            "binding",
            "remark",
        )
        import_id_fields = ("number",)
        export_order = fields

    @staticmethod
    def dehydrate_level(instance: TestCase):
        return DictData.objects.get(type="tms_tc_level", value=instance.level).label

    @staticmethod
    def dehydrate_type(instance: TestCase):
        return DictData.objects.get(type="tms_tc_type", value=instance.type).label

    @staticmethod
    def dehydrate_stage(instance: TestCase):
        return DictData.objects.get(type="tms_tc_stage", value=instance.stage).label

    @staticmethod
    def dehydrate_step(instance: TestCase):
        content = ""
        for step in instance.steps:
            content = content + "%s.%s\n" % (step.get("id"), step.get("step"))
        return content

    @staticmethod
    def dehydrate_exp(instance: TestCase):
        content = ""
        for step in instance.steps:
            content = content + "%s.%s\n" % (step.get("id"), step.get("exp"))
        return content

    @staticmethod
    def dehydrate_pcap(instance: TestCase):
        content = ""
        for step in instance.steps:
            content = content + "%s.%s\n" % (step.get("id"), step.get("pcap"))
        return content

    @staticmethod
    def dehydrate_rule(instance: TestCase):
        content = ""
        for step in instance.steps:
            content = content + "%s.%s\n" % (step.get("id"), step.get("rule"))
        return content

    @staticmethod
    def dehydrate_binding(instance: TestCase):
        content = ""
        for step in instance.steps:
            if step.get("binding"):
                if instance.type == "11":
                    binding = {
                        "product": step.get("binding")[0]["product"]["label"],
                        "packet": step.get("binding")[0]["packet"]["label"],
                        "field": step.get("binding")[0]["name"],
                    }
                else:
                    binding = {
                        "product": step.get("binding")[0]["product"]["label"],
                        "protocol": step.get("binding")[0]["protocol"]["label"],
                        "field": step.get("binding")[0]["name"],
                    }
                content = content + "%s.%s\n" % (step.get("id"), binding)
        return content
